package controller

import (
	"github.com/cn-ygf/go-admin/internal/action"
	"github.com/cn-ygf/go-admin/internal/modular/system/model"
	"github.com/cn-ygf/go-admin/internal/modular/system/service"
	"github.com/cn-ygf/go-admin/internal/modular/system/vo"
	"github.com/cn-ygf/go-admin/pkg/utils"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

type LoginLogController struct {
	Ctx iris.Context
}

// PostList 分页查询登录日志
func (c *LoginLogController) PostList(req *vo.QueryLoginLogListReq) mvc.Result {
	if !hasPermi(c.Ctx, "system:loginlog:list") {
		return nil
	}
	var (
		err   error
		list  []*model.SysLoginLog
		total int64
	)

	if req.PageSize > 1000 {
		req.PageSize = 1000
	}
	if req.Params != nil {
		req.Params.BeginTime = req.Params.BeginTime / 1000
		req.Params.EndTime = req.Params.EndTime / 1000
	}
	list, total, err = service.LoginLogService.QueryList(req)
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.ServerError()
	}
	return action.Data(map[string]any{
		"rows":  list,
		"total": total,
	})
}

// PostExport 导出日志
func (c *LoginLogController) PostExport(req *vo.ExportLoginLogReq) mvc.Result {
	if !hasPermi(c.Ctx, "system:loginlog:export") {
		return nil
	}
	var (
		err  error
		list []*model.SysLoginLog
	)
	if req.Params != nil {
		req.Params.BeginTime = req.Params.BeginTime / 1000
		req.Params.EndTime = req.Params.EndTime / 1000
	}
	list, err = service.LoginLogService.Export(req)
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.ServerError()
	}
	titleRow := []string{"编号", "用户名称", "IP地址", "登录地点", "浏览器标识", "状态", "描述", "登录时间"}
	statusMaps, err := service.DictDataService.GetDictMaps("sys_normal_disable")
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.RawError()
	}
	data := make([][]any, len(list))
	for index, item := range list {
		row := make([]any, 8)
		row[0] = item.InfoID
		row[1] = item.UserName
		row[2] = item.Ipaddr
		row[3] = item.LoginLocation
		row[4] = item.UserAgent
		row[5] = statusMaps[item.Status]
		row[6] = item.Msg
		row[7] = utils.UnixTimeToString(item.LoginTime)
		data[index] = row
	}
	return action.ExportExcel(data, titleRow)
}

// DeleteBy 删除登录日志
func (c *LoginLogController) DeleteBy(idStr string) mvc.Result {
	if !hasPermi(c.Ctx, "system:loginlog:remove") {
		return nil
	}
	ids := utils.IdsStrToInt64(idStr)
	if len(ids) < 1 {
		return action.ParamError()
	}
	if utils.IdsContains(ids, 1) {
		return action.AdminError()
	}
	err := service.LoginLogService.Delete(ids)
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.ServerError()
	}
	return action.OK()
}

// DeleteClean 清空日志
func (c *LoginLogController) DeleteClean() mvc.Result {
	if !hasPermi(c.Ctx, "system:loginlog:remove") {
		return nil
	}
	err := service.LoginLogService.Clean()
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.ServerError()
	}
	return action.OK()
}
